# -*- coding: utf-8 -*-

import logging
from datetime import datetime, timedelta

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError
from .excel_tools import  GenerateExcel

_logger = logging.getLogger(__name__)

months = [
    (1, u'一月'),
    (2, u'二月'),
    (3, u'三月'),
    (4, u'四月'),
    (5, u'五月'),
    (6, u'六月'),
    (7, u'七月'),
    (8, u'八月'),
    (9, u'九月'),
    (10, u'十月'),
    (11, u'十一月'),
    (12, u'十二月')
]

month_bill_headers = [
    ('日期', 3333),
    ('客户', 3343),
    ('品名', 3353),
    ('工艺类型', 4563),
    ('图案', 3373),
    ('匹数', 3000),
    ('结算方式', 3393),
    ('重量(Kg)', 3000),
    ('金额(元)', 3000)
]


def get_years():
    year_list = []
    for i in range(2018, 2049):
        year_list.append((i, str(i)))
    return year_list


def query_date(year, start_month, end_month):
    if start_month > end_month:
        start_month, end_month = end_month, start_month
    # 1~1 1.01 <= date < 2.01
    # 1~3 1.01 <= date < 4.01
    start_date = '%s-%s-01' % (year, start_month)
    end_date = '%s-%s-01' % (year, end_month+1)
    return start_date, end_date


class PartnerMonthBillWiz(models.TransientModel):
    _name = 'buliao.partner.month.bill.wiz'

    partner_id = fields.Many2one('res.partner', string=u'客户', required=True, domain=[('customer', '=', True)])
    year = fields.Selection(get_years(), string=u'年份', required=True)
    start_month = fields.Selection(months, string=u'开始月份', required=True)
    end_month = fields.Selection(months, string=u'结束月份', required=True)

    @api.multi
    def btn_report(self):
        self.ensure_one()
        query = {
                'partner_id': self.partner_id.id,
                'year': self.year,
                'start_month': self.start_month,
                'end_month': self.end_month
        }
        return {
            'type': 'ir.actions.client',
            'tag': 'buliao_export_month_bill',
            'params': {'query': query}
        }

    def get_month_bill_datas(self, query):
        # 日期 客户 品名 工艺类型 图案 匹数 结算方式 重量(Kg) 金额(元)
        partner_obj = self.env['res.partner']
        so_obj = self.env['sale.order']
        partner = partner_obj.browse(query['partner_id'])
        if not partner:
            # 导出对账单时，正好该用户被其他用户删除
            raise UserError(u'对账单对应的用户不存在!')
        query_partner_ids = [query['partner_id']]
        child_ids = partner.child_ids.filtered(lambda r: r.customer).mapped('id')
        if child_ids:
            query_partner_ids.extend(child_ids)
        start_date, end_date = query_date(query['year'], query['start_month'], query['end_month'])
        domain = [
            ('produce_state', '=', 'done'),
            ('partner_id', 'in', query_partner_ids),
            ('produce_done_date', '>=', start_date),
            ('produce_done_date', '<', end_date)
        ]
        sale_orders = so_obj.search(domain, order='produce_done_date asc')
        bill_datas = sale_orders.mapped(lambda r: [
            r.produce_done_date.split(' ')[0] if r.produce_done_date else '',
            r.partner_id.name,
            r.buliao_type,
            r.line_names,
            '',  # 图案
            r.buliao_qty,
            u'按毛重' if r.incoming_order_id.compute_method == 'weight' else u'按净重',
            r.buliao_weight if r.incoming_order_id.compute_method == 'weight' else r.buliao_net_weight,
            r.amount_total
        ])
        return bill_datas

    def export_month_bill(self, query, stream):
        bill_datas = self.get_month_bill_datas(query)
        excel = GenerateExcel(stream)
        excel.write_headers(month_bill_headers)
        sheets_rows = {
            'sheet': bill_datas
        }
        excel.write_sheets_rows(sheets_rows)
        # 合计
        end_row = len(bill_datas) + 1
        infos = {
            'sheet': [
                (end_row, 7, 'SUM(H1:H%s)' % end_row),
                (end_row, 8, 'SUM(I1:I%s)' % end_row),
            ]
        }
        excel.write_cell_formula(infos)
        excel.write_cell(end_row, 0, u'合计', ['sheet'])
        excel.save()

